package com.leo.foodmaster.commons.handler;

import com.leo.foodmaster.commons.constants.HttpStatus;
import com.leo.foodmaster.commons.entity.Result;
import com.leo.foodmaster.commons.exception.AuthenticationFailedException;
import com.leo.foodmaster.commons.exception.ImportException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import javax.servlet.http.HttpServletRequest;

/**
 * <p>
 * 全局异常处理器
 * </p>
 *
 * @author ：Leo
 * @since ：2021-06-19 11:21
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
    /**
     * 全局异常.
     * @param e the e
     */
    private void handleGlobalException(HttpServletRequest req, Exception e) {
        log.error("全局异常信息,url={}, ex={}", req.getRequestURI(), e.getMessage(), e);
    }

    /**
     * 认证失败异常处理
     */
    @ExceptionHandler(AuthenticationFailedException.class)
    public Result<Void> authenticationFailedException(HttpServletRequest req, AuthenticationFailedException e) {
        handleGlobalException(req, e);
        return Result.fail(e.getCode(), e.getMessage());
    }

    /**
     * 参数缺失异常处理
     */
    @ExceptionHandler(MissingServletRequestParameterException.class)
    public Result<Void> missingServletRequestParameterException(
                        HttpServletRequest req,
                        MissingServletRequestParameterException e) {
        handleGlobalException(req, e);
        return Result.fail(HttpStatus.BAD_REQUEST, e.getMessage());
    }

    /**
     * 导入失败异常处理
     */
    @ExceptionHandler(ImportException.class)
    public Result<Void> importException(HttpServletRequest req, ImportException e) {
        handleGlobalException(req, e);
        return Result.fail(HttpStatus.IMPORT_FAILED, e.getMessage());
    }
}
